package com.dianrui.qiyouriding.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.SPUtils;
import com.dianrui.qiyouriding.Constant;
import com.dianrui.qiyouriding.MyApplication;
import com.dianrui.qiyouriding.R;
import com.dianrui.qiyouriding.bean.NewMobile;
import com.dianrui.qiyouriding.event.RfreshUnread;
import com.dianrui.qiyouriding.util.AESCBCUtils;
import com.dianrui.qiyouriding.util.MD5;
import com.dianrui.qiyouriding.util.MyUtil;
import com.dianrui.qiyouriding.util.NoDoubleClickUtils;
import com.dianrui.qiyouriding.okhttp.OkHttpRequest;
import com.dianrui.qiyouriding.util.PhoneCode;
import com.dianrui.qiyouriding.util.RSAUtils;
import com.dianrui.qiyouriding.util.SharedUtil;
import com.dianrui.qiyouriding.util.StringUtils;
import com.dianrui.qiyouriding.util.ToastUtil;
import com.dianrui.qiyouriding.util.Url;
import com.dianrui.qiyouriding.view.CountDownButton;
import com.google.gson.JsonObject;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Random;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 登录界面
 * 如果需要按左上角或者扫码用车则必须登录
 */
@SuppressWarnings("ALL")
public class LoginActivity extends BaseActivity {
    private PhoneCode mPhoneCode;

    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.login_mobile)
    EditText loginMobile;
    @BindView(R.id.countdown)
    CountDownButton countdown;
    @BindView(R.id.login_password)
    EditText loginPassword;
    @BindView(R.id.login_btn)
    Button loginBtn;

    @Override
    public int getContentViewId() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {
        EventBus.getDefault().register(this);
        customInit(true, R.color.main_color);
        title.setText(getString(R.string.login_txt));
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_SMS)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.RECEIVE_SMS)
                != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this, new String[]
                    {Manifest.permission.READ_SMS, Manifest.permission.RECEIVE_SMS}, 1);

        }
        countdown.setOnOperationCallBack(new CountDownButton.CountDownButtonOperationCallBack() {
            @Override
            public void onFinish() {
                countdown.millisInFuture(60000);
                countdown.setText(getString(R.string.login_txt2));
                countdown.setTextColor(Color.WHITE);
            }

            @Override
            public void onTick(long millisUntilFinished, CountDownButton countDownButton) {
                String tickTxts = millisUntilFinished / 1000 + "秒后再试";
                countdown.setText(tickTxts);
                countdown.setTextColor(Color.WHITE);
            }

            @Override
            public void onClickFromUser(boolean isRunning, long millisUntilFinished, CountDownButton countDownButton) {
                getVerificationCode();
            }
        });
        loginMobile.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 11) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm != null) {
                        imm.hideSoftInputFromWindow(loginMobile.getWindowToken(), 0);
                    }
                    if (!StringUtils.isEmpty(loginMobile.getText().toString()) && !StringUtils.isEmpty(loginPassword.getText().toString())) {
                        loginBtn.setBackgroundResource(R.drawable.yellow_gradient);
                        loginBtn.setEnabled(true);
                    } else {
                        loginBtn.setBackgroundResource(R.drawable.gray_shape);
                    }
                } else {
                    loginBtn.setBackgroundResource(R.drawable.gray_shape);
                }

            }
        });
        loginPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 6) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm != null) {
                        imm.hideSoftInputFromWindow(loginPassword.getWindowToken(), 0);
                    }
                    if (!StringUtils.isEmpty(loginMobile.getText().toString()) && !StringUtils.isEmpty(loginPassword.getText().toString())) {
                        loginBtn.setBackgroundResource(R.drawable.yellow_gradient);
                        loginBtn.setEnabled(true);
                    } else {
                        loginBtn.setBackgroundResource(R.drawable.gray_shape);
                    }
                } else {
                    loginBtn.setBackgroundResource(R.drawable.gray_shape);
                    loginBtn.setEnabled(false);
                }

            }
        });
        mPhoneCode = new PhoneCode(this, new Handler(), loginMobile.getText().toString(), new PhoneCode.SmsListener() {
                    @Override
                    public void onResult(String result) {
                        loginPassword.setText(result);
                    }
                });
        // 注册短信变化监听
        getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, mPhoneCode);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(NewMobile newMobile) {
        loginMobile.setText(newMobile.number);
    }



    @Override
    public void initData() {
    }

    @Override
    protected void onPause() {
        super.onPause();

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    /**
     * 获取验证码
     */
    public void getVerificationCode() {
        if (StringUtils.isEmpty(loginMobile.getText().toString())) {
            ToastUtil.showToast("请输入你的手机号码");
            return;
        }
        if (loginMobile.getText().length() < 11) {
            ToastUtil.showToast("手机号码必须是11位");
            return;
        }

        if (countdown.getmCurrentmillis() > 2000) {
            ToastUtil.showToast(countdown.getmCurrentmillis() / 1000 + "秒后再试");
            return;
        }
        showLoadingDialog("正在发送短信中...");
        JsonObject jsonObject = new JsonObject();
        JsonObject jsonObject1 = new JsonObject();
        jsonObject1.addProperty("account",loginMobile.getText().toString());
        jsonObject1.addProperty("type","1");

        jsonObject.addProperty("content",  getMd5(jsonObject1.toString()));
        OkHttpRequest.getInstance().postRequests(Url.GETCODE, jsonObject.toString(),  new OkHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                countdown.start();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else {
                                dismissLoadingDialog();
                                countdown.cancel();
                                countdown.setText(getString(R.string.getcode_txt));
                                countdown.setTextColor(Color.WHITE);
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }

            @Override
            public void failedRequest(String result) {
                dismissLoadingDialog();
                countdown.cancel();
                countdown.setText(getString(R.string.getcode_txt));
                countdown.setTextColor(Color.WHITE);
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    public static  String getMd5(String json){
        String aes_key = getSeqNo(16);
        //rsa公钥
        String default_rsa_public_key =Constant.RAS;

        String plantText = json;
        String aes_str = AESCBCUtils.encrypt(plantText, aes_key); //aes密文
        String rsa_str = RSAUtils.encrypt(aes_key, default_rsa_public_key); //rsa密文--公钥加密
        String md5_str = "";
        try {
            md5_str = MD5.digest(aes_key+ plantText);
        } catch (Exception e) {
            e.printStackTrace();
        }
        StringBuffer sb = new StringBuffer();
        sb.append(md5_str).append(RSAUtils.SEPARATOR).append(RSAUtils.SEPARATOR).append(aes_str).append(RSAUtils.SEPARATOR).append(RSAUtils.SEPARATOR).append(rsa_str);
        return sb.toString();
    }

    /**
     * 生成16位随机字符串
     * @return
     */
    public static final String getSeqNo(int len){
        String randomStr = "qwertyuiopasdfghjklzxcvbnm1234567890QWERTYUIOPASDFGHJKLZXCVBNM";
        StringBuilder stringBuilder = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < len; i++) {
            stringBuilder.append(randomStr.charAt(random.nextInt(randomStr.length())));
        }
        return stringBuilder.toString();
    }

    @OnClick({R.id.back, R.id.login_btn, R.id.user_protocol, R.id.user_privacy})
    public void onViewClicked(View view) {
        if (NoDoubleClickUtils.isDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.back:
                JumpActivitys(MainActivity.class);
                finish();
                break;
            case R.id.login_btn:
                if (StringUtils.isEmpty(loginMobile.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.login_txt7));
                } else if (StringUtils.isEmpty(loginPassword.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.login_txt8));
                } else {
                    startLogin();
                }
                break;

            case R.id.user_protocol:
                startActivity(new Intent(LoginActivity.this, WebViewActivity.class).putExtra("type", "useagree"));
                break;

            case R.id.user_privacy:
                startActivity(new Intent(LoginActivity.this, WebViewActivity.class).putExtra("type", "secret"));
                break;

            default:
                break;
        }
    }


    //开始登录
    private void startLogin() {
        showLoadingDialog(getString(R.string.login_txt9));
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("account", loginMobile.getText().toString().trim());
        jsonObject.addProperty("verify_code", loginPassword.getText().toString().trim());
        jsonObject.addProperty("device_number", MyUtil.getUniqueId(LoginActivity.this));
        jsonObject.addProperty("type", "1");
        jsonObject.addProperty("device_type", MyUtil.getSystemBARND() + "  " + MyUtil.getSystemModel());
        jsonObject.addProperty("app_version", MyUtil.getAppInfo(LoginActivity.this));
        jsonObject.addProperty("device_version", MyUtil.getOS());
        OkHttpRequest.getInstance().postNormalRequests(Url.LOGIN, jsonObject.toString(), new OkHttpRequest.XCallBack() {
            @Override
            public void onResponse(String response) {
                if (!StringUtils.isEmpty(response)) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                               SPUtils.getInstance().put("member_id", jsonObject.optJSONObject("data").optString("member_id"),true);//用户ID，非常重要，必须获取
                               SPUtils.getInstance().put("account", jsonObject.optJSONObject("data").optString("account"),true);//账户
                               SPUtils.getInstance().put("email", jsonObject.optJSONObject("data").optString("email"),true);//电子邮件
                               SPUtils.getInstance().put("mobile", jsonObject.optJSONObject("data").optString("mobile"),true);//手机
                               SPUtils.getInstance().put("nickname", jsonObject.optJSONObject("data").optString("nickname"),true);//昵称
                               SPUtils.getInstance().put("scan_url", jsonObject.optJSONObject("data").optString("scan_url"),true);
                               SPUtils.getInstance().put("name", jsonObject.optJSONObject("data").optString("name"),true);//用户名字
                               SPUtils.getInstance().put("card", jsonObject.optJSONObject("data").optString("card"),true);//认证
                               SPUtils.getInstance().put("face", jsonObject.optJSONObject("data").optString("face"),true);//头像地址(无需拼接)
                               SPUtils.getInstance().put("token", jsonObject.optJSONObject("data").optString("token"),true);//token
                               SPUtils.getInstance().put("is_account", jsonObject.optJSONObject("data").optString("is_account"),true);//是否认证
                               SPUtils.getInstance().put("state", jsonObject.optJSONObject("data").optString("state"),true);//登录状态
                               SPUtils.getInstance().put("join_tel", jsonObject.optJSONObject("data").optString("join_tel"),true);//加盟电话
                               SPUtils.getInstance().put("service_tel", jsonObject.optJSONObject("data").optString("service_tel"),true);//客服电话
                               SPUtils.getInstance().put("safety_url", jsonObject.optJSONObject("data").optString("safety_url"),true);//网页
                               SPUtils.getInstance().put("remark", jsonObject.optJSONObject("data").optString("remark"),true);//remark
                               SPUtils.getInstance().put("is_partner", jsonObject.optJSONObject("data").optInt("is_partner"));//is_partner
                               SPUtils.getInstance().put("is_deposit", jsonObject.optJSONObject("data").optString("is_deposit"));//是否有押金
                               SPUtils.getInstance().put("is_bank_card", jsonObject.optJSONObject("data").optString("is_bank_card"));//是否绑定银行卡
                                SharedUtil.setToken(jsonObject.optJSONObject("data").optString("token"));
                                SharedUtil.setMemberToken(jsonObject.optJSONObject("data").optString("member_token"));
                                MyApplication.initJiGuangUser(jsonObject.optJSONObject("data").optString("token"), LoginActivity.this);//绑定推送别名

                                if (StringUtils.isEmpty(jsonObject.optJSONObject("data").optString("card"))) {//没有认证跳认证
                                    Intent intent=new Intent(LoginActivity.this, AuthActivity.class);
                                    Bundle bundle=new Bundle();
                                    bundle.putString("isBackAuth", "2");
                                    intent.putExtras(bundle);
                                    startActivity(intent);
                                    finish();
                                    return;
                                }

                                if ("0".equals(jsonObject.optJSONObject("data").optString("is_deposit"))) {
                                    Intent intent=new Intent(LoginActivity.this, DepositActivity.class);
                                    Bundle bundle=new Bundle();
                                    bundle.putString("isDespoitBack", "2");
                                    bundle.putString("isborrowCar", "0");
                                    intent.putExtras(bundle);
                                    startActivity(intent);
                                    finish();
                                    return;
                                }
                                if (countdown != null) {
                                    countdown.cancel();
                                }
                                if (mPhoneCode != null) {
                                    getContentResolver().unregisterContentObserver(mPhoneCode);
                                }
                                startActivity(new Intent(LoginActivity.this, MainActivity.class));//跳主页
                                EventBus.getDefault().post(new RfreshUnread());
                                switch (jsonObject.optJSONObject("data").optString("state")) {//判断登录状态
                                    case "0":
                                        JumpActivitys(MainActivity.class);
                                        finish();
                                        break;
                                    case "1":
                                        JumpActivitys(MainActivity.class);
                                        finish();
                                        break;
                                    case "2":
                                        ToastUtil.showToast("您的账号已被锁定,请联系后台");
                                        break;
                                    case "3":
                                        ToastUtil.showToast("您的账号已被封号,请联系后台");
                                        break;
                                    default:
                                        ToastUtil.showToast("您的账号状态未知,请联系后台");
                                        break;
                                }
                            } else {
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                dismissLoadingDialog();
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            JumpActivitys(MainActivity.class);
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }




    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (countdown != null) {
            countdown.destroy();
        }
        if (mPhoneCode != null) {
            getContentResolver().unregisterContentObserver(mPhoneCode);
        }
    }
}
